package com.kingmed.kmss.admin.modules.ums.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.kingmed.kmss.admin.modules.sys.service.SysDataDictService;
import com.kingmed.kmss.admin.modules.ums.mapper.UmsOrganizationMapper;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdmin;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdminOrganizationRelation;
import com.kingmed.kmss.admin.modules.ums.model.UmsKmcsOrg;
import com.kingmed.kmss.admin.modules.ums.model.UmsOrganization;
import com.kingmed.kmss.admin.qc.AdminQc;
import com.kingmed.kmss.admin.modules.ums.service.*;
import com.kingmed.kmss.common.dto.admin.ums.OrgNodeDTO;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationDTO;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationTileDTO;
import com.kingmed.kmss.common.enums.admin.OrgLevel;
import com.kingmed.kmss.common.enums.admin.UserSource;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.common.service.sys.RedisService;
import com.kingmed.kmss.common.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台组织机构表 服务实现类
 * </p>
 */
@Slf4j
@Service
public class UmsOrganizationServiceImpl extends ServiceImpl<UmsOrganizationMapper, UmsOrganization> implements UmsOrganizationService {

    /**
     * 组织层级数据字典Code
     */
    private static final String DICT_ORG_LEVEL_CODE = "ums_org_level_code";

    /**
     * 缓存所有组织机构key
     */
    private static final String REDIS_UMS_ORGANIZATION = "ums_organization:all";

    /**
     * 组织有效
     */
    public static final Integer STATUS_YES = 0;

    /**
     * 集团的组织ID 固定
     */
    public static final Long GROUP_ORG_ID = 1L;

    @Autowired
    private UmsAdminOrganizationRelationService organizationRelationService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysDataDictService dataDictService;
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private UmsBpmnMembershipService bpmnMembershipService;
    @Autowired
    private UmsKmcsOrgService umsKmcsOrgService;


    /**
     * orgId及所有的children，并返回列表
     */
    @Override
    public List<OrgNodeDTO> selfAndChild(Long orgId) {
        OrgNodeDTO tree = tree(orgId);
        List<OrgNodeDTO> result = new ArrayList<>();
        recursionTreeToList(result, tree, null);
        return result;
    }

    @Override
    public String selfAndChildString(Long orgId) {
        List<OrgNodeDTO> orgNodeDtos = selfAndChild(orgId);
        List<String> collect = orgNodeDtos.stream()
                .filter(org -> org.getId() != null)
                .map(org -> org.getId().toString())
                .collect(Collectors.toList());
        return String.join(",", collect);
    }


    /**
     * 找到orgId及所有的children，并返回树状结构
     */
    @Override
    public OrgNodeDTO tree(Long orgId) {
        return this.getTreeData(orgId,
                this.list(new LambdaQueryWrapper<UmsOrganization>()
                        .eq(UmsOrganization::getStatus, STATUS_YES)
                        .orderByAsc(UmsOrganization::getLevel))
        );
    }

    /**
     * 找到orgId及所有的children，并返回树状结构，仅查询到子公司层级
     */
    @Override
    public OrgNodeDTO tree3Level(Long orgId) {
        return this.getTreeData(orgId,
                this.list(new LambdaQueryWrapper<UmsOrganization>()
                        .eq(UmsOrganization::getStatus, STATUS_YES)
                        .le(UmsOrganization::getLevel, OrgLevel.BRANCH.getCode())
                        .orderByAsc(UmsOrganization::getLevel))
        );
    }

    /**
     * 找到orgId及所有的children，并返回树状结构，仅查询子公司以下层级
     *
     * @param orgId   组织ID
     * @param onlyOrg 是否只显示部门
     */
    @Override
    public OrgNodeDTO tree4Level(Long orgId, Boolean onlyOrg) {
        return this.getTreeData(orgId, this.loadAllOrg());
    }

    private OrgNodeDTO getTreeData(Long orgId, List<UmsOrganization> list) {
        UmsOrganization org = this.getById(orgId);
        OrgNodeDTO tree = new OrgNodeDTO();
        BeanCopyUtils.copy(org, tree);

        // 组织层级名称
        Map<String, String> levelMap = dataDictService.queryMapByCode(DICT_ORG_LEVEL_CODE);

        //遍历list
        List<OrgNodeDTO> nodes = list.stream()
                //过滤，找出节点
                .filter(node -> node.getParentId().equals(orgId))
                //遍历每一个ParentId = orgId 的node，转类型，同时通过递归转换成树状结构
                .map(node -> transform(node, list, levelMap))
                .collect(Collectors.toList());
        tree.setChildren(nodes);
        tree.setLevelName(levelMap.get(String.valueOf(tree.getLevel())));
        return tree;
    }

    /**
     * 树状转list
     */
    @Override
    public void recursionTreeToList(List<OrgNodeDTO> result, OrgNodeDTO root, OrgNodeDTO parentNode) {
        result.add(root);
        if (CollectionUtils.isEmpty(root.getChildren())) {
            return;
        }
        for (OrgNodeDTO child : root.getChildren()) {
            this.recursionTreeToList(result, child, root);
        }
    }

    /**
     * 根据名称关键字模糊查询
     */
    @Override
    public List<UmsOrganization> getByNameKey(String keyword) {
        return this.list(new LambdaQueryWrapper<UmsOrganization>().like(UmsOrganization::getOrgName, keyword));
    }

    /**
     * 新增或修改
     */
    @Transactional
    @Override
    public List<UmsOrganization> updateOrg(OrgNodeDTO orgNodeDto) {
        List<OrgNodeDTO> orgNodeDtoList = new ArrayList<>();
        this.recursionTreeToList(orgNodeDtoList, orgNodeDto, null);

        List<UmsOrganization> umsOrganizationList = new ArrayList<>();
        for (OrgNodeDTO child : orgNodeDtoList) {
            UmsOrganization organization = new UmsOrganization();
            BeanCopyUtils.copy(child, organization);
            if (organization.getStatus() == null) {
                // 生效
                organization.setStatus(STATUS_YES);
            }
            umsOrganizationList.add(organization);
        }
        this.saveOrUpdateBatch(umsOrganizationList);

        this.redisAllOrg();
        return umsOrganizationList;
    }

    /**
     * 逻辑删除
     */
    @Transactional
    @Override
    public int deleteOrg(List<Long> orgIdList) {
        for (Long orgId : orgIdList) {
            List<OrgNodeDTO> orgNodeDtoList = this.selfAndChild(orgId);
            if (orgNodeDtoList != null && orgNodeDtoList.size() > 1) {
                throw new BusinessException(orgNodeDtoList.get(0).getOrgName() + "存在有效子机构，不能删除");
            }
        }
        List<UmsOrganization> organizations = this.list(new LambdaQueryWrapper<UmsOrganization>().in(UmsOrganization::getId, orgIdList));
        for (UmsOrganization organization : organizations) {
            // 删除状态
            organization.setStatus(0);
        }
        this.updateBatchById(organizations);

        this.redisAllOrg();
        return organizations.size();
    }

    /**
     * 生效
     */
    @Transactional
    @Override
    public int availableOrg(List<Long> orgIdList) {
        List<UmsOrganization> organizations = this.list(new LambdaQueryWrapper<UmsOrganization>().in(UmsOrganization::getId, orgIdList));
        for (UmsOrganization organization : organizations) {
            organization.setStatus(1);
        }
        this.updateBatchById(organizations);
        return organizations.size();
    }

    /**
     * 根据orgId获取组织机构下用户
     */
    @Override
    public List<UmsAdmin> adminsInOrg(Long orgId) {
        return this.getBaseMapper().adminsInOrg(orgId);
    }


    /**
     * 根据orgId获取组织机构及下级组织机构 用户
     */
    @Override
    public Page<UmsAdmin> adminsInOrgAndChild(AdminQc adminQc) {
        Page<UmsAdmin> page = new Page<>(adminQc.getPageNum(), adminQc.getPageSize());
        // 取组织机构及下级组织机构ID
        List<Long> orgAndChildIdList = Lists.newArrayList();
        Long orgId = adminQc.getOrgId();
        if (orgId != null) {
            List<OrgNodeDTO> orgList = this.selfAndChild(orgId);
            for (OrgNodeDTO orgNodeDto : orgList) {
                if (!orgAndChildIdList.contains(orgNodeDto.getId())) {
                    orgAndChildIdList.add(orgNodeDto.getId());
                }
            }
        }
        Page<UmsAdmin> umsAdminPage = this.getBaseMapper().adminsInOrgAndChildNew(page, orgAndChildIdList, adminQc);
        if (umsAdminPage != null && umsAdminPage.getRecords() != null) {
            for (UmsAdmin record : umsAdminPage.getRecords()) {
                List<UmsOrganization> adminOrg = umsAdminService.getOrgList(record.getId());
                record.setOrgId(CollectionUtils.isEmpty(adminOrg) ? 1 : adminOrg.get(0).getId());
                if (UserSource.CRM_USER.getUserType().equals(record.getUserSource())) {
                    record.setOrgFullName(this.getAdminOrgFullName(record.getOrgId()));
                }
                this.handleDirectLeaderName(record);
            }
        }
        return umsAdminPage;
    }

    private void handleDirectLeaderName(UmsAdmin record) {
        if (StrUtil.isBlank(record.getDirectLeader())) {
            record.setDirectLeaderName(StrUtil.EMPTY);
            return;
        }
        List<UmsAdmin> adminList = umsAdminService.list(new QueryWrapper<UmsAdmin>().lambda().eq(UmsAdmin::getUsername, record.getDirectLeader()));
        if (CollectionUtil.isNotEmpty(adminList)) {
            record.setDirectLeaderName(adminList.get(0).getNickName());
        }
    }

    @Override
    public String getAdminOrgFullName(Long orgId) {
        UmsOrganization org = this.getById(orgId);
        if (org == null)
            return null;
        List<UmsOrganization> orgList = this.getParentUpList(this.loadAllOrg(), org.getId());
        StringBuilder orgFullName = new StringBuilder(StrUtil.EMPTY);
        if (CollectionUtils.isNotEmpty(orgList)) {
            orgList.sort(Comparator.comparing(UmsOrganization::getLevel));
            for (UmsOrganization item : orgList) {
                orgFullName.append(item.getOrgName()).append("_");
            }
        }
        orgFullName.append(org.getOrgName());
        return orgFullName.toString();
    }

    /**
     * 根据组织编码查询组织全称
     *
     * @param orgCode
     * @return
     */
    @Override
    public String findAdminOrgFullName(String orgCode) {
        UmsOrganization org = this.getOne(new LambdaQueryWrapper<UmsOrganization>().eq(UmsOrganization::getOrgCode, orgCode).last("limit 1"));
        List<UmsOrganization> orgList = this.getParentUpList(this.loadAllOrg(), org.getId());
        StringBuilder orgFullName = new StringBuilder(StrUtil.EMPTY);
        if (CollectionUtils.isNotEmpty(orgList)) {
            orgList.sort(Comparator.comparing(UmsOrganization::getLevel));
            for (UmsOrganization item : orgList) {
                orgFullName.append(item.getOrgName()).append("_");
            }
            orgFullName.append(org.getOrgName());
        }
        return orgFullName.toString();
    }


    @Override
    public List<UmsAdmin> allAdminsInOrg(AdminQc adminQc) {
        if (BeanUtil.isEmpty(adminQc.getOrgId())) {
            return Lists.newArrayList();
        }
        // 取组织机构及下级组织机构ID
        List<OrgNodeDTO> orgList = this.selfAndChild(adminQc.getOrgId());
        if (CollectionUtils.isEmpty(orgList)) {
            return Lists.newArrayList();
        }
        List<Long> orgAndChildIdList = Lists.newArrayList();
        for (OrgNodeDTO orgNodeDto : orgList) {
            if (!orgAndChildIdList.contains(orgNodeDto.getId())) {
                orgAndChildIdList.add(orgNodeDto.getId());
            }
        }
        return this.getBaseMapper().adminsInOrgAndChild(orgAndChildIdList, adminQc);
    }


    /**
     * 修改用户的部门
     */
    @Transactional
    @Override
    public void addAdminsInOrg(List<UmsAdminOrganizationRelation> relations) {
        if (CollUtil.isNotEmpty(relations)) {
            this.deleteAdminsInOrg(relations);
            organizationRelationService.saveBatch(relations);
            UmsAdmin admin = umsAdminService.getById(relations.get(0).getAdminId());
            //更新admin表的org_full_name
            admin.setOrgFullName(this.getAdminOrgFullName(relations.get(0).getOrgId()));
            umsAdminService.saveOrUpdate(admin);
            // 更新审批角色与用户关联关系表
            for (UmsAdminOrganizationRelation relation : relations) {
                bpmnMembershipService.updateBranchRegion(relation.getAdminId());
            }
        }
    }

    /**
     * 组织机构下删除用户
     */
    @Override
    public void deleteAdminsInOrg(List<UmsAdminOrganizationRelation> relations) {
        if (!relations.isEmpty()) {
            for (UmsAdminOrganizationRelation relation : relations) {
                this.getBaseMapper().deleteIgnoreLogic(relation);
            }
        }
    }

    /**
     * 递归，在orgs找source的子节点，没有就停止递归
     */
    private OrgNodeDTO transform(UmsOrganization source, List<UmsOrganization> orgs, Map<String, String> levelMap) {
        //当前节点source copy to node
        OrgNodeDTO node = new OrgNodeDTO();
        BeanUtil.copyProperties(source, node);

        node.setLevelName(levelMap.get(node.getLevel().toString()));

        List<OrgNodeDTO> children = orgs.stream()
                .filter(child -> child.getParentId().equals(source.getId()) && child.getLevel() > source.getLevel())
                .map(child -> transform(child, orgs, levelMap))
                .collect(Collectors.toList());
        //set到node
        node.setChildren(children);
        return node;
    }

    /**
     * 根据orgId找到子公司
     * （可能需要从账号的所属分部的名称来判断，oa账号和数据中台组织数据，没有严格的层级关系，目前看下来子公司和大区是同一个层级）
     */
    @Override
    public UmsOrganization getBranchOrg(List<UmsOrganization> allOrg, Long orgId) {
        List<UmsOrganization> parentUpList = getParentUpList(allOrg, orgId);
        if (CollectionUtils.isEmpty(parentUpList)) {
            return null;
        }
        List<UmsOrganization> collect = parentUpList.stream()
                .filter(item -> item.getLevel().equals(OrgLevel.BRANCH.getCode()))
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            return collect.get(0);
        }
        return null;
    }

    public List<UmsOrganization> getParentUpList(List<UmsOrganization> allOrg, Long orgId) {
        UmsOrganization current = getById(orgId);
        List<UmsOrganization> ancestors = new ArrayList<>();
        if (current != null && current.getParentId() != 0) {
            //找到父节点
            List<UmsOrganization> collect = allOrg.stream()
                    .filter(item -> item.getId().equals(current.getParentId()))
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                ancestors.add(collect.get(0));
                List<UmsOrganization> orgUpTree = getParentUpList(allOrg, collect.get(0).getId());
                if (orgUpTree != null) {
                    ancestors.addAll(orgUpTree);
                }
                return ancestors;
            }
        }
        return Lists.newArrayList();
    }

    public List<UmsOrganization> loadAllOrg() {
        List<UmsOrganization> cache = (List<UmsOrganization>) redisService.get(REDIS_UMS_ORGANIZATION);
        if (BeanUtil.isNotEmpty(cache)) {
            return cache;
        }
        return this.redisAllOrg();
    }

    /**
     * 更新组织缓存
     *
     * @return
     */
    @Override
    public List<UmsOrganization> redisAllOrg() {
        List<UmsOrganization> all = list(new LambdaQueryWrapper<UmsOrganization>()
                .eq(UmsOrganization::getStatus, STATUS_YES)
                .orderByAsc(UmsOrganization::getLevel));
        redisService.set(REDIS_UMS_ORGANIZATION, all);
        return all;
    }

    /**
     * 用户ID获取全部子公司
     * 子公司层级类型 orgType=3
     */
    @Override
    public List<OrganizationDTO> getSubsidiaryByAdminId(Long adminId) {
        List<UmsOrganization> adminOrgList = umsAdminService.getOrgList(adminId);
        List<UmsOrganization> allOrgList = this.loadAllOrg();
        List<OrganizationDTO> result = Lists.newArrayList();
        // 一个用户只有一个组织
        if (!CollectionUtils.isEmpty(adminOrgList)) {
            UmsOrganization userOrg = this.getUpOrgIdNotBranchType(adminOrgList.get(0), allOrgList);
            this.handleBranchesInfo(userOrg, result, allOrgList);
        }
        return result;
    }

    @Override
    public List<OrganizationDTO> getBranchesByOrgId(Long orgId) {
        List<UmsOrganization> allOrgList = this.loadAllOrg();
        UmsOrganization org = this.getUpOrgIdNotBranchType(this.getById(orgId), allOrgList);
        List<OrganizationDTO> result = Lists.newArrayList();
        this.handleBranchesInfo(org, result, allOrgList);
        return result;
    }

    /**
     * 根据orgID获取直属上级集团、大区、子公司对象
     */
    private UmsOrganization getUpOrgIdNotBranchType(UmsOrganization userOrg, List<UmsOrganization> allOrgList) {
        List<UmsOrganization> parentUpList = this.getParentUpList(allOrgList, userOrg.getId());
        parentUpList.add(0, userOrg);
        for (UmsOrganization org : parentUpList) {
            if (org.getLevel() <= OrgLevel.BRANCH.getCode()) {
                return org;
            }
        }
        return userOrg;
    }

    private void handleBranchesInfo(UmsOrganization userOrg, List<OrganizationDTO> result, List<UmsOrganization> allOrgList) {
        // 用户=子公司
        if (OrgLevel.BRANCH.getCode().equals(userOrg.getLevel())) {
            result.add(BeanCopyUtils.copy(userOrg, OrganizationDTO.class));
        }
        // 用户=子公司下级 向上找子公司
        if (userOrg.getLevel() > OrgLevel.BRANCH.getCode()) {
            List<UmsOrganization> parentUpList = this.getParentUpList(allOrgList, userOrg.getId());
            parentUpList.stream()
                    .filter(umsOrg -> OrgLevel.BRANCH.getCode().equals(umsOrg.getLevel()))
                    .map(umsOrg -> BeanCopyUtils.copy(umsOrg, OrganizationDTO.class))
                    .forEach(result::add);
        }
        // 用户=子公司上级 向下找子公司
        if (userOrg.getLevel() < OrgLevel.BRANCH.getCode()) {
            OrgNodeDTO tree = this.tree3Level(userOrg.getId());
            List<OrgNodeDTO> organizations = new ArrayList<>();
            recursionTreeToList(organizations, tree, null);
            organizations.stream().filter(organization -> OrgLevel.BRANCH.getCode().equals(organization.getLevel()))
                    .map(organization -> BeanCopyUtils.copy(organization, OrganizationDTO.class)).forEach(result::add);
        }
    }

    /**
     * 获取所有大区
     */
    @Override
    public List<OrganizationDTO> getRegions() {
        List<UmsOrganization> all = this.list(new LambdaQueryWrapper<UmsOrganization>()
                .eq(UmsOrganization::getStatus, STATUS_YES)
                .eq(UmsOrganization::getLevel, OrgLevel.REGION.getCode())
                .orderByAsc(UmsOrganization::getOrgCode));
        return BeanCopyUtils.copyList(all, OrganizationDTO.class);
    }

    /**
     * 获取所有大区(sql)
     */
    @Override
    public List<OrganizationDTO> getRegionsBySql() {
        return BeanCopyUtils.copyList(this.getBaseMapper().getRegionsBySql(), OrganizationDTO.class);
    }

    /**
     * 获取所有子公司
     */
    @Override
    public List<OrganizationDTO> getAllSubsidiary() {
        List<UmsOrganization> all = this.list(new LambdaQueryWrapper<UmsOrganization>()
                .eq(UmsOrganization::getStatus, STATUS_YES)
                .eq(UmsOrganization::getLevel, OrgLevel.BRANCH.getCode()));
        return BeanCopyUtils.copyList(all, OrganizationDTO.class);
    }

    @Override
    public Map<Long, OrganizationDTO> getOrgByIds(List<Long> orgIds) {
        Map<Long, OrganizationDTO> result = new HashMap<>();
        if (CollectionUtils.isEmpty(orgIds)) {
            return result;
        }
        for (Long orgId : orgIds) {
            result.put(orgId, BeanCopyUtils.copy(this.getBaseMapper().selectById(orgId), OrganizationDTO.class));
        }
        return result;
    }

    /**
     * 组织机构DTO：所属集团、大区、子公司平铺
     */
    @Override
    public OrganizationTileDTO getOrgGroupRegionBranchByOrgId(Long orgId) {
        UmsOrganization umsOrganization = this.getById(orgId);
        List<UmsOrganization> parentUpList = new ArrayList<>();
        parentUpList.add(umsOrganization);
        List<UmsOrganization> parents = this.getParentUpList(this.loadAllOrg(), orgId);
        OrganizationTileDTO resultDTO = new OrganizationTileDTO();
        //如果有上级节点，才放进去
        if (CollectionUtils.isNotEmpty(parents)) {
            parentUpList.addAll(parents);
        }
        for (UmsOrganization org : parentUpList) {
            // 集团
            if (OrgLevel.GROUP.getCode().equals(org.getLevel())) {
                resultDTO.setGroupId(org.getId());
                resultDTO.setGroupName(org.getOrgName());
                //找kmcs的code
                UmsKmcsOrg umsKmcsOrg = umsKmcsOrgService.getBaseMapper().selectOne(new QueryWrapper<UmsKmcsOrg>().lambda()
                        .eq(UmsKmcsOrg::getOrgId, org.getId()));
                if (ObjectUtil.isNotNull(umsKmcsOrg)) {
                    resultDTO.setGroupCodeKmcs(umsKmcsOrg.getKmcsCode());
                }
            }
            // 大区
            if (OrgLevel.REGION.getCode().equals(org.getLevel())) {
                resultDTO.setRegionId(org.getId());
                resultDTO.setRegionName(org.getOrgName());
                //找kmcs的code
                UmsKmcsOrg umsKmcsOrg = umsKmcsOrgService.getBaseMapper().selectOne(new QueryWrapper<UmsKmcsOrg>().lambda()
                        .eq(UmsKmcsOrg::getOrgId, org.getId()));
                if (ObjectUtil.isNotNull(umsKmcsOrg)) {
                    resultDTO.setRegionCodeKmcs(umsKmcsOrg.getKmcsCode());
                }
            }
            // 子公司
            if (OrgLevel.BRANCH.getCode().equals(org.getLevel())) {
                resultDTO.setSubCompanyId(org.getId());
                resultDTO.setSubCompanyName(org.getOrgName());
                //找kmcs的code
                UmsKmcsOrg umsKmcsOrg = umsKmcsOrgService.getBaseMapper().selectOne(new QueryWrapper<UmsKmcsOrg>().lambda()
                        .eq(UmsKmcsOrg::getOrgId, org.getId()));
                if (ObjectUtil.isNotNull(umsKmcsOrg)) {
                    resultDTO.setSubCompanyCodeKmcs(umsKmcsOrg.getKmcsCode());
                }
            }
            // 孙公司（原则上，孙公司如果上线kmcs和crm，将被当作子公司对待）
            if (OrgLevel.BRANCH_CHILD.getCode().equals(org.getLevel())) {
                resultDTO.setSubChildCompanyId(org.getId());
                resultDTO.setSubChildCompanyName(org.getOrgName());
                //找kmcs的code
                UmsKmcsOrg umsKmcsOrg = umsKmcsOrgService.getBaseMapper().selectOne(new QueryWrapper<UmsKmcsOrg>().lambda()
                        .eq(UmsKmcsOrg::getOrgId, org.getId()));
                if (ObjectUtil.isNotNull(umsKmcsOrg)) {
                    resultDTO.setSubChildCompanyCodeKmcs(umsKmcsOrg.getKmcsCode());
                }
            }
        }

        return resultDTO;
    }

    /**
     * 查询用户有权限 的所有组织树
     */
    @Override
    public OrgNodeDTO queryPermissionOrg(Long adminId) {
        // 一个用户只有一个组织
        List<UmsOrganization> orgList = umsAdminService.getOrgList(adminId);
        return BeanUtil.isNotEmpty(orgList) ? this.handlePermissionOrg(orgList.get(0)) : null;
    }

    /**
     * 查询某个组织有权限 的所有组织树
     */
    @Override
    public OrgNodeDTO queryPermissionByOrgId(Long orgId) {
        UmsOrganization userOrg = this.getBaseMapper().selectById(orgId);
        return BeanUtil.isNotEmpty(userOrg) ? this.handlePermissionOrg(userOrg) : null;
    }

    private OrgNodeDTO handlePermissionOrg(UmsOrganization userOrg) {
        List<UmsOrganization> parentAndSelf = Lists.newArrayList();
        if (BeanUtil.isNotEmpty(userOrg)) {
            List<UmsOrganization> allOrg = this.loadAllOrg();
            List<UmsOrganization> parentUpList = this.getParentUpList(allOrg, userOrg.getId());
            parentAndSelf.add(userOrg);
            parentAndSelf.addAll(parentUpList);
        }
        OrgNodeDTO group = null;
        OrgNodeDTO region = null;
        OrgNodeDTO branch = null;
        for (UmsOrganization umsOrg : parentAndSelf) {
            if (OrgLevel.GROUP.getCode().equals(umsOrg.getLevel())) {
                group = BeanCopyUtils.copy(umsOrg, OrgNodeDTO.class);
            }
            if (OrgLevel.REGION.getCode().equals(umsOrg.getLevel())) {
                region = BeanCopyUtils.copy(umsOrg, OrgNodeDTO.class);
            }
            if (OrgLevel.BRANCH.getCode().equals(umsOrg.getLevel())) {
                branch = BeanCopyUtils.copy(umsOrg, OrgNodeDTO.class);
            }
        }
        // 上级为子公司
        if (group != null && region != null && branch != null) {
            region.setChildren(Lists.newArrayList());
            region.getChildren().add(branch);
            group.setChildren(Lists.newArrayList());
            group.getChildren().add(region);

        }
        // 上级为大区
        if (group != null && region != null && branch == null) {
            OrgNodeDTO orgNodeDto = this.tree3Level(region.getId());
            group.setChildren(Lists.newArrayList());
            group.getChildren().add(orgNodeDto);
        }
        // 上级集团
        if (group != null && region == null && branch == null) {
            group = this.tree3Level(group.getId());
        }
        return group;
    }

    @Override
    public List<OrgNodeDTO> directChild(Long orgId) {
        List<UmsOrganization> entityList = this.list(new LambdaQueryWrapper<UmsOrganization>()
                .eq(UmsOrganization::getStatus, STATUS_YES).eq(UmsOrganization::getParentId, orgId)
                .orderByAsc(UmsOrganization::getLevel));
        List<OrgNodeDTO> dtoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(entityList)) {
            // 组织层级名称
            Map<String, String> levelMap = dataDictService.queryMapByCode(DICT_ORG_LEVEL_CODE);

            for (UmsOrganization org : entityList) {
                OrgNodeDTO dto = BeanUtil.copyProperties(org, OrgNodeDTO.class);
                dto.setHasChildren(this.hasChild(org.getId()));
                dto.setLevelName(levelMap.get(dto.getLevel().toString()));
                dtoList.add(dto);
            }
        }
        return dtoList;
    }

    private boolean hasChild(Long orgId) {
        List<UmsOrganization> entityList = this.list(new LambdaQueryWrapper<UmsOrganization>()
                .eq(UmsOrganization::getStatus, STATUS_YES).eq(UmsOrganization::getParentId, orgId));
        return CollectionUtils.isNotEmpty(entityList);
    }

    /**
     * 组织树前三层的树形结构
     */
    @Override
    public OrgNodeDTO levelThreeOrgTree() {
        List<UmsOrganization> allOrg = this.loadAllOrg();
        List<UmsOrganization> level3UpOrgList = new ArrayList<>();
        List<Long> level2OrgIdList = new ArrayList<>();
        for (UmsOrganization org : allOrg) {
            if (GROUP_ORG_ID.equals(org.getId())) {
                org.setHasChildren(false);
                level3UpOrgList.add(org);
            }
            if (GROUP_ORG_ID.equals(org.getParentId())) {
                org.setHasChildren(false);
                level3UpOrgList.add(org);
                level2OrgIdList.add(org.getId());
            }
        }
        for (UmsOrganization org : allOrg) {
            if (level2OrgIdList.contains(org.getParentId())) {
                org.setHasChildren(true);
                level3UpOrgList.add(org);
            }
        }
        return this.getTreeData(GROUP_ORG_ID, level3UpOrgList);
    }

    @Override
    public List<OrganizationDTO> groupRegionBranch(Integer orgLevel) {
        return this.getBaseMapper().groupRegionBranch(orgLevel);
    }

}
